package com.abu.ums.service.impl;

import com.abu.ums.pojo.Member;
import com.abu.ums.mapper.MemberMapper;
import com.abu.ums.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author 阿布
 * @since 2020-06-13
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberMapper memberMapper;

    private static final String PREFIX = "USM.";
    private static final String MES_PREFIX = "UMS.CODE";

    @Override
    public void sendCode(String phone) {
        this.amqpTemplate.convertAndSend(PREFIX + "PHONE", phone);
    }

    @Override
    public Boolean saveMember(Member member, String code) {
//        获取缓存的验证码
        String codeFromRedis = this.redisTemplate.opsForValue().get(MES_PREFIX);
        if (StringUtils.isBlank(code)) {
            return false;
        }
//        从缓存中获取的验证码与用户输入验证码进行比较
        if (!StringUtils.equals(code, codeFromRedis)) {
            return false;
        }
//        对密码加盐加密
        member.setPassword(this.passwordEncoder.encode(member.getPassword()));
//        保存用户
        boolean flag = this.save(member);
        if (!flag) {
            return false;
        }
//        删除验证码
        this.redisTemplate.delete(MES_PREFIX);
        return true;
    }

    @Override
    public Member login(String nickname, String rawPassword) {
//        根据用户名查询出用户密码
        Member member = this.getOne(new QueryWrapper<Member>().eq("nickname", nickname));
        if (member == null) {
            return null;
        }
//        核对密码
        boolean flag = this.passwordEncoder.matches(rawPassword, member.getPassword());
            if (!flag) {
            return null;
        }
        return member;
    }

}
